package dao;

import data.Manager;
import data.Student;
import service.DbConnect;
import service.Tool;
import zhujie.Select;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

public class StudentDao{
    private static DbConnect<Student> c=new DbConnect();
    private static Student stu=new Student();
   public static List listAll(){
       try {
           return c.selectList("select * from student",stu);
       }
       catch (Exception e){
           System.out.println("错误"+e.getMessage());
           return null;
       }
   }

   public static Student one(int id){
       try{
           return c.selectOne("select * from student where id="+id,stu);
       }catch (Exception e){
           System.out.println("错误"+e.getMessage());
           return null;
       }
   }

   public static boolean add(Student stu) throws Exception {
       String sql="insert into student (name,user,pwd,class_id) values"+stu.simplSql();
       return c.execute(sql);
   }

   public static boolean del(int id) throws Exception{
       String sql="delete table student where id="+id;
       return c.execute(sql);
   }
   public static boolean edit(String type,String val,int id){
       try {
           String sql="update student set ?=? where id=?";
           PreparedStatement preparedStatement = c.preparedStatement(sql);
           preparedStatement.setString(1,type);
           preparedStatement.setString(2,val);
           preparedStatement.setInt(3,id);
           c.que(preparedStatement);
           return true;
       } catch (SQLException e) {
           System.out.println("错误："+e.getMessage());
           return false;
       }
   }

    public static String login(Student m) throws Exception {
        Student manager = c.selectOne("select * from manager where user=" + m.getUser() + " and pwd=" + m.getPwd(), m);
        if(manager==null)
            return null;
        else{
            String session= Tool.session();
            insertToken(manager.getId(),session);
            return session;
        }
    }

    public static void insertToken(int id,String session) throws Exception {
        String sql="update student set session="+ session+" where id="+id;
        c.execute(sql);
    }
}
